"""
    监听超时队列

    只要存在消息 就读出
        1. 修改mysql订单历史
        2. 加入redis相关超时键
"""

from redis_operator import enter_overtime
from rabbitmq_operator import rabbit_conn
import json
from handle_db import init_overtime_order


def overtime_order(ch, method, properties, body):
    # 如果是超时 则修改数据库中状态。否则是已完成的订单
    body = str(body, encoding="utf-8")
    body = json.loads(body)
    print("我是overtime_order", body)
    if enter_overtime(body):
        print("我要将其状态修改为已超时")
        init_overtime_order(body)
    ch.basic_ack(delivery_tag=method.delivery_tag)


def start_overtime_consume():
    channel = rabbit_conn.channel()
    # 延迟交换机死信收容交换机
    exchange = 'overtime.exchange'
    # 延迟队列死信收容队列
    queue = 'overtime.queue'
    channel.exchange_declare(exchange=exchange,
                             exchange_type='fanout',
                             durable=True
                             )
    channel.queue_declare(queue=queue, durable=True)
    channel.queue_bind(queue=queue, routing_key='', exchange=exchange)
    print("我是延时队列的消费者，我要开始接收消息了")
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_message_callback=overtime_order,
                          queue=queue,
                          auto_ack=False)
    channel.start_consuming()


start_overtime_consume()
